﻿using Oracle.ManagedDataAccess.Client;
using Server.Constant;
using Server.Enum;
using Server.OptExp;
using Server.Framework.Message;
using Server.Framework.Processor;
using Server.Framework.Service;
using Server.Framework.Socket;
using Server.Message.Request;
using Server.Message.Response;
using Server.Model;
using System.Data.Common;
using System.Runtime.InteropServices;
using System;

namespace Server.Processor
{
    /// <summary>
    /// Author: Leil
    /// Description: 新增或编辑用户操作
    /// CreateTime: 2020/5/13 10:12:49
    /// </summary>
    [ProcessorAttr(MessageId.ADD_EDIT_USER)]
    class AddEditUserProcessor : IProcessor
    {

        public void Process(ProtobufAppSession session, RequestBaseMessage message)
        {
            if (session.User == null)
            {
                Console.WriteLine("用户未登录");
                return;
            }

            if (message is AddEditUserReq msg)
            {
                OperationResp resp = new OperationResp(MessageId.OPT_RESP);
                if (msg.UserDao == null)
                {
                    resp.Code = 500;
                    resp.OptType = (int)OptType.ADD_EDIT_USER;
                    resp.Content = "用户不能为空";
                    session.Send(resp);
                    return;
                } else
                {
                    try
                    {
                        if (msg.UserDao.ID != 0)
                        {
                            EditUser(msg, session);
                        }
                        else
                        {
                            AddUser(msg, session);
                        }
                    }
                    catch (CommonOptException e)
                    {
                        resp.Code = 500;
                        resp.OptType = (int)OptType.ADD_EDIT_USER;
                        resp.Content = e.Message;
                        session.Send(resp);
                    }
                }
            }
        }


        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="role">用户</param>
        /// <param name="resp">消息</param>
        private void AddUser(AddEditUserReq msg, ProtobufAppSession session)
        {
            //if (user.OrgId == 0)
            //{
            //    throw new CommonOptException("组织机构ID不能为空");
            //}
            UserDao user = msg.UserDao;
            if (string.IsNullOrEmpty(user.LoginName)) {
                throw new CommonOptException("登录名称不能为空");
            }
            if (string.IsNullOrEmpty(user.Password))
            {
                throw new CommonOptException("登录密码不能为空");
            }

            string insertSql = $@"INSERT INTO SYS_USER ( ID, ORG_ID, LOGIN_NAME, PASSWORD, STATUS, SORT, CREATOR, CREATE_TIME )
VALUES
	( seq_sys_user.NEXTVAL, {user.OrgId}, '{user.LoginName}', '{user.Password}', {user.Status}, {user.Sort}, '{session.User.LoginName}', sysdate )";

            string queryIdSql = "SELECT seq_sys_user.currval FROM dual";

            DbConnection connection = DBService.Instance().GetConnection();
            try
            {
                connection.Open();
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = insertSql;
                    command.ExecuteNonQuery();
                    command.CommandText = queryIdSql;
                    int lastInsertId = 0;
                    using (DbDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            lastInsertId = Convert.ToInt32(reader["CURRVAL"]);
                        }
                    }
                    msg.RoleIds.ForEach(roleId =>
                    {
                        string allotRoleSql = $"INSERT INTO SYS_USER_ROLE (USER_ID, ROLE_ID) VALUES ({lastInsertId}, {roleId})";
                        command.CommandText = allotRoleSql;
                        command.ExecuteNonQuery();
                    });
                }
                connection.Close();
                OperationResp resp = new OperationResp(MessageId.OPT_RESP)
                {
                    Code = 200,
                    OptType = (int)OptType.ADD_EDIT_USER,
                    Content = "添加成功"
                };
                session.Send(resp);
            }
            catch (Exception e)
            {
                throw new CommonOptException(e.Message);
            }finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="role">用户</param>
        /// <param name="resp">消息</param>
        private void EditUser(AddEditUserReq msg, ProtobufAppSession session)
        {
            UserDao user = msg.UserDao;
            string updateSql = $@"UPDATE SYS_USER 
SET ORG_ID = {user.OrgId},
LOGIN_NAME = '{user.LoginName}',
PASSWORD = '{user.Password}',
STATUS = {user.Status},
SORT = {user.Sort},
UPDATOR = '{session.User.LoginName}',
UPDATE_TIME = sysdate 
WHERE ID = {user.ID}";

            string deleteSql = $"DELETE FROM SYS_USER_ROLE WHERE USER_ID={user.ID}";


            DbConnection connection = DBService.Instance().GetConnection();
            try
            {
                connection.Open();
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = updateSql;
                    command.ExecuteNonQuery();
                    command.CommandText = deleteSql;
                    command.ExecuteNonQuery();
                    msg.RoleIds.ForEach(roleId =>
                    {
                        string allotRoleSql = $"INSERT INTO SYS_USER_ROLE (USER_ID, ROLE_ID) VALUES ({user.ID}, {roleId})";
                        command.CommandText = allotRoleSql;
                        command.ExecuteNonQuery();
                    });
                }
                connection.Close();
                OperationResp resp = new OperationResp(MessageId.OPT_RESP)
                {
                    Code = 200,
                    OptType = (int)OptType.ADD_EDIT_USER,
                    Content = "更新成功"
                };
                session.Send(resp);
            }
            catch (Exception e)
            {
                throw new CommonOptException(e.Message);
            }finally
            {
                connection.Close();
            }

        }


    }
}
